<template>
  <div>
    <top-bar></top-bar>
    <left-bar :datas='data'></left-bar>
    <div class="container main">
      <div class="main-mains-top">
        编辑问卷
      </div>
      <div class="publicTable toLongTable">
        <div class="main-returns">
          <i class="el-icon-arrow-left" @click="returns()"></i>
          <span @click="returns()">返回</span>
        </div>
        <div class="main-meeting">
          <div class="main-meetings clear">
            <div class="main-meetings-l">问卷标题：</div>
            <div class="fl">
              <el-input v-model.trim="title" clearable placeholder="请输入问卷标题"></el-input>
            </div>
          </div>
          <div class="main-meetings clear">
            <div class="main-meetings-l">问卷说明：</div>
            <div class="fl">
              <el-input v-model.trim="description" type="textarea" resize='none' clearable placeholder="请输入问卷说明"></el-input>
            </div>
          </div>
          <div class="main-meetings clear">
            <div class="main-meetings-l">问卷类型：</div>
            <div class="fl  meetings-radio">
              <el-radio v-model="questionType" :label="1">问答</el-radio>
              <el-radio v-model="questionType" :label="2">调研</el-radio>
            </div>
          </div>
          <div class="main-meetings clear">
            <div class="main-meetings-l">问卷时间：</div>
            <div class="fl ">
              <el-date-picker v-model="time" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </div>
          <div class="main-meetings clear">
            <div class="main-meetings-l">分数积分设置：</div>
            <div class="fl main-meetings-score">
              <div v-for="(item,index) in integralRatio " :key="index" class="main-meetings-scores">
                <el-input v-model="item.score1"></el-input>
                <span class="main-meetings-txt">至</span>
                <el-input v-model="item.score2"></el-input>
                <span class="main-meetings-txt">获得积分的占比：</span>
                <el-input v-model="item.ratio" placeholder="请输入比例"></el-input>
                <span class="integral-ratio" @click="addRatio()">添加</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="qu-wrap">
        <div class="qu-content">
          <section class="qu-item" v-for="(item, index) in questions" :key="index" :class="{nowEditing: curIndex === index && topicEditing, optEditing: curIndex === index}">
            <h3 @click="curIndex = index; curOptIndex=''; topicEditing = true">
              <span class="qu-num">{{`Q${index + 1}`}}</span>
              <span class="qu-topic">{{ item.topic }}</span>
              <input type="text" v-model="topic" @focus="_topic = topic" @blur="curIndex=''; topic=''" @keyup.enter="doneTopicEdit(index)">
            </h3>
            <template v-if="item.type === 'textarea'">
              <textarea rows="8" cols="80"></textarea>
            </template>
            <ul v-else class="options-list">
              <li v-for="(option, optIndex) in item.options" :key="optIndex" :class="{optionEditing: curOptIndex === optIndex}">
                <span class="optionText" @click="curIndex=index; curOptIndex=optIndex; topicEditing = false">{{ option.content }}</span>
                <input type="text" v-model="optionText" @focus="_optionText = optionText" @blur="curIndex=''; optionText=''" @keyup.enter="doneOptionEdit(index, optIndex)">
                <ul class="opt-ctrl">
                  <li v-show="option.is_right">
                    <span>此题为答案</span>
                  </li>
                  <label v-show="!option.is_right">
                    <input type="radio" name='answer' v-model="option.is_right" @change="getAnswer(index,optIndex)">选为答案
                  </label>
                  <li v-if="optIndex !== 0" @click="moveUp(optIndex, item.options)">上移</li>
                  <li v-if="optIndex !== item.options.length - 1" @click="moveDown(optIndex, item.options)">下移</li>
                  <li v-else @click="addOption(item.options)">添加</li>
                  <li @click="delOption(optIndex, item.options)">删除</li>
                </ul>
              </li>
            </ul>
            <ul class="operat-list">
              <li>
                <span @click="curIndex = index; curOptIndex=''; topicEditing = true">此题分数{{item.score}}</span>&nbsp;
                <input type="text" v-model="score" @focus="_score = score" @blur="score=''" @keyup.enter="doneScoreEdit(index)" placeholder="请输入该题分数">
              </li>
              <li v-if="index !== 0" @click="moveUp(index,questions)">上移</li>
              <li v-if="index !== questions.length - 1" @click="moveDown(index,questions)">下移</li>
              <li @click="reuse(index)">复用</li>
              <li @click="delQuestion(index)">删除</li>
            </ul>
          </section>
          <div class="add-box">
            <p class="qu-type" :class="{expand: isAdding}">
              <span @click="addType('judge')">判断题</span>
              <span @click="addType('radio')">单选题</span>
              <span @click="addType('checkbox')">多选题</span>
              <span @click="addType('textarea')">文本题</span>
            </p>

            <p class="add-btn" @click="isAdding = !isAdding;">
              <span>+ 添加问题</span>
            </p>
          </div>
        </div>
        <footer>
          <div class="date-part">
          </div>
          <div class="ctrl-part">
            <span @click="saveBtn()">确定编辑</span>
          </div>
        </footer>
      </div>
    </div>
  </div>
</template>

<script>
import leftBar from "@/components/leftBar";
import topBar from "@/components/topBar";
import Data from "../data.js";
import questionnaire from "@/api/questionnaire";
export default {
  components: {
    leftBar,
    topBar
  },
  data() {
    return {
      data: "questionnaire",
      index: "",
      questions: [],
      questionTemplate: {},
      date: "",
      title: "",
      description: "",
      questionType: "",
      topic: [],
      _topic: "",
      optionText: "",
      _optionText: "",
      curIndex: "",
      curOptIndex: "",
      promptText: "",
      isAdding: false,
      topicEditing: false,
      score: "",
      _score: "",
      isright: "",
      time: [],
      integralRatio: [{ score1: "", score2: "", ratio: "" }],
      id: this.$route.query.id
    };
  },

  mounted() {
    this.getData();
    this.getDetails();
  },
  methods: {
    getDetails() {
      const options = {
        id: this.id
      };
      questionnaire.getDetail(options).then(res => {
        if (res.code == 1) {
          this.title = res.data.title;
          this.description = res.data.description;
          this.questionType = res.data.type;
          this.time[0] = res.data.starttime;
          this.time[1] = res.data.expires;

          let scoreInterval = JSON.parse(res.data.score_interval);
          for (let i = 0; i < res.data.quesion.length; i++) {
            let option = JSON.parse(res.data.quesion[i].option);
            let types;
            switch (res.data.quesion[i].type) {
              case 0:
                types = "radio";
                break;
              case 1:
                types = "radio";
                break;
              case 2:
                types = "checkbox";
                break;
              case 3:
                types = "textarea";
                break;
            }
            this.questions.push({
              topic: res.data.quesion[i].subject,
              score: res.data.quesion[i].score,
              options: option,
              quesionType: res.data.quesion[i].type,
              type: types
            });
          }
          this.integralRatio = [];
          for (let i = 0; i < res.data.score_interval.length; i++) {
            this.integralRatio.push({
              score1: scoreInterval[i].between[0],
              score2: scoreInterval[i].between[1],
              ratio: scoreInterval[i].score
            });
          }
        }
      });
    },
    returns() {
      history.go(-1);
    },
    addRatio() {
      for (let i = 0; i < this.integralRatio.length; i++) {
        if (
          this.integralRatio[i].score1 == "" ||
          this.integralRatio[i].score2 == "" ||
          this.integralRatio[i].ratio == ""
        ) {
          this.$message({
            showClose: true,
            message: "请先编辑当前的积分设置！",
            type: "error"
          });
          return false;
        }
      }
      this.integralRatio.push({ score1: "", score2: "", ratio: "" });
    },
    getData() {
      this.questionTemplate = Data.template;
    },
    getAnswer(index, optIndex) {
      if (this.questions[index].type == "radio") {
        for (let i = 0; i < this.questions[index].options.length; i++) {
          this.questions[index].options[i].is_right = 0;
        }
      }
      this.questions[index].options[optIndex].is_right = 1;
    },
    doneTopicEdit(index) {
      this.topicEditing = false;
      this.questions[index].topic = this.topic;
    },

    doneOptionEdit(index, optIndex) {
      this.curOptIndex = "";
      this.questions[index].options[optIndex].content = this.optionText;
    },
    doneScoreEdit(index) {
      this.topicEditing = false;
      this.questions[index].score = this.score;
    },

    switchItem(index, array) {
      this.optIndex = "";
      this.curIndex = "";

      let arr = array.splice(index, 2);
      array.splice(index, 0, ...arr.reverse());
    },

    moveUp(index, array) {
      this.switchItem(index - 1, array);
    },

    moveDown(index, array) {
      this.switchItem(index, array);
    },

    reuse(index) {
      let oldQuestion = this.questions[index];
      let newQuestion = JSON.parse(JSON.stringify(oldQuestion));
      this.questions.splice(index, 0, newQuestion);
    },

    delQuestion(index) {
      if (this.questions.length <= 1) {
        this.errorPrompt(`每份问卷至少一个问题！`);
        return;
      }
      this.questions.splice(index, 1);
    },

    delOption(index, options) {
      if (options.length <= 2) {
        this.errorPrompt(`每个问题至少两个选项`);
        return;
      }
      options.splice(index, 1);
    },

    addOption(options) {
      options.push({ content: "请输入编辑内容", is_right: 0 });
    },

    addType(type) {
      let newQuestion = JSON.parse(JSON.stringify(this.questionTemplate[type]));
      this.questions.splice(this.questions.length, 0, newQuestion);
    },

    saveBtn() {
      if (this.title == "") {
        this.$message({
          showClose: true,
          message: "请输入问卷标题！",
          type: "success"
        });
        return false;
      }
      if (this.description == "") {
        this.$message({
          showClose: true,
          message: "请输入问卷说明！",
          type: "success"
        });
        return false;
      }

      let questionsArr;
      questionsArr = [];
      for (let i = 0; i < this.questions.length; i++) {
        if (this.questions.type != "textarea") {
          questionsArr.push({
            subject: this.questions[i].topic,
            type: this.questions[i].quesionType,
            score: this.questions[i].score,
            option: this.questions[i].options
          });
        } else {
          questionsArr.push({
            subject: this.questions[i].topic,
            type: this.questions[i].quesionType,
            score: this.questions[i].score,
            option: "  "
          });
        }
      }
      let scoreArr = [];
      for (let i = 0; i < this.integralRatio.length; i++) {
        scoreArr.push({
          between: [this.integralRatio[i].score1, this.integralRatio[i].score2],
          score: this.integralRatio[i].ratio
        });
      }
      const options = {
        id: this.id,
        title: this.title,
        description: this.description,
        type: this.questionType,
        score_interval: scoreArr,
        quesion: questionsArr,
        starttime: this.time[0],
        expires: this.time[1]
      };
      questionnaire.edit(options).then(res => {
        if (res.code == 1) {
          this.$message({
            showClose: true,
            message: "编辑问卷成功！",
            type: "success"
          });
        }
      });
    },
    errorPrompt(value) {
      this.$message({
        showClose: true,
        message: value,
        type: "error"
      });
    }
  }
};
</script>

<style scoped lang="less">
@import "css/edit.less";
</style>
